package com.lhr.common.util;

import java.util.Calendar;
import java.util.Date;

public class DateUtil {

	/**
	 * 清除日期的:时,分,秒,毫秒
	 */
	public static Calendar clearHMSM(Calendar calendar) {
		calendar.clear(Calendar.SECOND);
		calendar.clear(Calendar.MILLISECOND);
		calendar.clear(Calendar.MINUTE);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		// calendar.clear(Calendar.HOUR); 用这个并不可以重置,api有说明
		return calendar;
	}

	/**
	 * 得到当天最大的时间,如：2011-12-12 23:59:59
	 */
	public static Calendar getMaxTimeInDay(Calendar calendar) {
		calendar.set(Calendar.SECOND, 59);
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		return calendar;
	}

	/**
	 * 得到当天最大的时间,如：2011-12-12 23:59:59
	 */
	public static Calendar getMaxTimeInDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return getMaxTimeInDay(calendar);
	}

	/**
	 * 清除日期的:时,分,秒,毫秒
	 */
	public static Calendar clearHMSM(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return clearHMSM(calendar);
	}

	public static long distance(Date beforeDate,
			Date afterDate,
			int calendarField) {
		long distance = beforeDate.getTime() - afterDate.getTime();
		if (calendarField == Calendar.MILLISECOND)
			return distance;
		else if (calendarField == Calendar.SECOND)
			return distance * 1000;
		else if (calendarField == Calendar.MINUTE)
			return distance / 1000 / 60;
		else if (calendarField == Calendar.HOUR)
			return distance / 1000 / 60 / 60;
		else if (calendarField == Calendar.DATE)
			return distance / 1000 / 60 / 60 / 24;
		else
			throw new RuntimeException("没有匹配的calendarField");
	}

}
